package edu.maping.easy.sequence;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import processing.core.PApplet;
import processing.xml.XMLElement;

import edu.maping.easy.model.PhysicPolyThing;
import edu.maping.easy.model.PolygonThing;
import edu.maping.easy.model.Thing;

public class SequenceStep {

	public Map<Thing, ActionEventList> actionEventMap = new Hashtable<Thing, ActionEventList>();

	public void draw(PApplet pApplet) {
		Iterator<Thing> set = actionEventMap.keySet().iterator();

		while (set.hasNext()) {
			Thing thing = set.next();
			ActionEventList actionEventList = actionEventMap.get(thing);
			for (ActionEvent actionEvent : actionEventList) {
				if (actionEvent.actionConf == null) {
					System.out
							.println("Se borrÃ³ una configuraciÃ³n pero no desapareciÃ³ del listado");
				} else {
					actionEvent.update(pApplet, thing);
				}
			}
		}
	}

	public XMLElement xmlIzation() {
		Set<Thing> things = actionEventMap.keySet();
		XMLElement stepElement = new XMLElement();
		stepElement.setName("Step");

		for (Thing thing : things) {

			XMLElement thingElement = new XMLElement();
			thingElement.setName("Thing");
			thingElement.setAttribute("id", "" + thing.getId());

			ActionEventList eventList = actionEventMap.get(thing);

			for (ActionEvent event : eventList) {
				XMLElement eventElement = event.xmlIzation();
				thingElement.addChild(eventElement);
			}

			stepElement.addChild(thingElement);
		}

		return stepElement;
	}

	public SequenceStep desXmlIzation(XMLElement xmlElement) {

		SequenceStep thingActionEvent = null;

		if (xmlElement.getName().equals("Step")) {
			thingActionEvent = new SequenceStep();
			for (XMLElement thingElement : xmlElement.getChildren()) {
				PolygonThing thing = new PolygonThing();
				String idString = thingElement.getAttribute("id");
				thing.setId(Long.parseLong(idString));

				ActionEventList actionEventList = new ActionEventList();
				for (XMLElement event : thingElement.getChildren()) {
					ActionEvent actionEvent = new ActionEvent();
					actionEvent = actionEvent.DesXmlIzation(event);
					actionEventList.add(actionEvent);
				}

				thingActionEvent.actionEventMap.put(thing, actionEventList);
			}
		}

		return thingActionEvent;

	}

}
